package cn.edu.neu.controller.user;

import cn.edu.neu.model.User;
import cn.edu.neu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("toLogin")
    public String toLoginPage(){
        return "/user/login";
    }
    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, Model model) {
        User user = userService.getUserByUsernameAndPassword(username, password);
        if (user != null) {
            session.setAttribute("currentUser", user);
            return "redirect:/index";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "/user/login";
        }
    }
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("currentUser");
        session.invalidate();
        return "redirect:/index";

    }
    @GetMapping("/status")
    @ResponseBody
    public String getCurrentUserStatus(HttpServletRequest request) {
        // 从 HttpSession 中获取当前登录用户的信息
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        return  String.valueOf(currentUser.getStatus());

    }
}
